package com.maiyuren.flutter_text_reader;

import androidx.annotation.NonNull;

import org.json.JSONObject;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

/** FlutterTextReaderPlugin */
public class FlutterTextReaderPlugin implements FlutterPlugin, MethodCallHandler {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  public static MethodChannel channel;

  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
    channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "flutter_text_reader");
    channel.setMethodCallHandler(this);

    flutterPluginBinding.getPlatformViewRegistry().registerViewFactory("com.maiyuren.sudict/fluttertextreader", new TextReaderPlatformViewFactory());
  }

  @Override
  public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
    if (call.method.equals("getPlatformVersion")) {
      result.success("Android " + android.os.Build.VERSION.RELEASE);
    }
    else if (call.method.equals("load")) {
      try {
        JSONObject args = new JSONObject((String)call.arguments);
        int id = (int) args.get("id");
        TextReaderPlatformView platformView = TextReaderPlatformView.s_views.get(id);
        if (platformView != null) {
          platformView.view.load((String) args.get("path"), (boolean) args.get("isHor"));
        }
        result.success(true);
      } catch (Exception ex){}
    }
    else {
      result.notImplemented();
    }
  }

  @Override
  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
    channel.setMethodCallHandler(null);
  }
}
